<script setup>
  import { ref } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { http } from '@/utils/http.js'
  import { useUsercodeStore } from '@/store/usercode.js'

  // 创建 Store 实例
  let userCodeStore = null
  // 设置头像
  const avatarToken = ref()
  const url = ref()
  const avatarUrl = ref()
  async function onChooseAvatar(e) {
    console.log(e)
    // 七牛云
    const res = await http.request({
      url: '/api/config/qiUpload',
      method: 'POST',
      data: {},
    })
    avatarToken.value = res.data.uptoken
    url.value = res.data.domain
    //将头像保存到后端
    uni.uploadFile({
      url: 'https://upload-z0.qiniup.com/',
      filePath: e.detail.avatarUrl, //头像文件
      header: {},
      formData: {
        token: avatarToken.value,
      },
      name: 'file',
      success: async (uploadFileRes) => {
        console.log(uploadFileRes.data)
        avatarUrl.value = url.value + JSON.parse(uploadFileRes.data).key
        const res = await http.request({
          url: '/api/user/upUser',
          method: 'POST',
          data: {
            field: 'himg',
            val: avatarUrl.value,
          },
        })
        if (res.st == 1) {
          uni.utils.toast('设置头像成功')
          userCodeStore.setHimg(avatarUrl.value)
        } else {
          uni.utils.toast(res.msg)
        }
      },
    })
  }

  function changeAvatar() {
    // uni.showActionSheet({
    // 	// itemList按钮的文字接受的是数组
    // 	itemList: ['查看头像', '从相册选择图片'],
    // 	success(e) {
    // 		var index = e.tapIndex
    // 		if (index === 0) {
    // 			// 用户点击了预览当前图片
    // 			// 可以自己实现当前头像链接的读取
    // 			let url = userCodeStore.usercode.himg
    // 			let arr = []
    // 			arr.push(url)
    // 			uni.previewImage({
    // 				// 预览功能图片也必须是数组的
    // 				urls: arr,
    // 			})
    // 		} else if (index === 1) {
    uni.navigateTo({
      // 跳转到图片处理页面,并将图片地址通过参数传递过去
      url: '/minePage/meface/index',
    })
    // 		}
    // 	},
    // })
  }

  const nickname = ref('')
  const token = ref('')
  const nick = ref('')
  const editpopup = ref()
  const currentId = ref()
  function goEdit() {
    editpopup.value.open('center')
  }
  function canceledit() {
    editpopup.value.close('center')
  }
  async function editName() {
    // const userCodeStore = useUsercodeStore()
    if (nickname.value.length > 7) {
      uni.utils.toast('昵称不得超过七位')
    }
    const res = await http.request({
      url: '/api/user/upUser',
      method: 'POST',
      data: {
        field: 'nickname',
        val: nickname.value,
      },
    })
    if (res.st == 1) {
      uni.utils.toast('编辑成功')
      userCodeStore.setNickname(nickname.value)
      editpopup.value.close('center')
    } else {
      uni.utils.toast(res.msg)
    }
  }

  //设置动画
  async function ifAnimation(e) {
    console.log(e.detail.value)
    if (e.detail.value == true && userCodeStore.usercode.animation != 1) {
      const res = await http.request({
        url: '/api/user/upUser',
        method: 'POST',
        data: {
          field: 'is_animation',
          val: '1',
        },
      })
      if (res.st == 1) {
        uni.utils.toast('开启成功')
        userCodeStore.setAnimation(1)
      } else {
        uni.utils.toast('开启失败')
      }
    } else if (
      e.detail.value == false &&
      userCodeStore.usercode.animation == 1
    ) {
      const res = await http.request({
        url: '/api/user/upUser',
        method: 'POST',
        data: {
          field: 'is_animation',
          val: '0',
        },
      })
      if (res.st == 1) {
        uni.utils.toast('关闭成功')
        userCodeStore.setAnimation(0)
      } else {
        uni.utils.toast('关闭失败')
      }
    }
  }

  //退出登录
  function logOut() {
    // const userCodeStore = useUsercodeStore()
    userCodeStore.resetToken()
    uni.clearStorageSync()
    setTimeout(() => {
      uni.reLaunch(
        {
          url: `/pages/login/login`,
        },
        80
      )
    })
  }

  // 注销账号
  const accountpopup = ref()
  function delAccount() {
    accountpopup.value.open('center')
  }
  function cancelaccount() {
    accountpopup.value.close('center')
  }
  async function accountName() {
    const res = await http.request({
      url: '/api/user/zxUser',
      method: 'POST',
      data: {},
    })
    if (res.st == 1) {
      uni.utils.toast('注销成功,返回登录页')
      setTimeout(() => {
        uni.reLaunch({
          url: `/pages/login/login`,
        })
      }, 2000)
    } else {
      uni.utils.toast('注销失败')
    }
  }

  //隐藏接口

  const shebei = ref(process.env.VUE_APP_PLATFORM)

  function goRule(id) {
    uni.navigateTo({
      url: `/homePage/agreement/index?id=${id}`,
    })
  }
  onLoad(() => {
    userCodeStore = useUsercodeStore()
    nickname.value = userCodeStore.usercode.nickname
    token.value = userCodeStore.usercode.token
  })
  onShow(() => {})
  function nickNameChange(e) {
    console.log(e)
  }
</script>

<template>
  <view class="setting-list" v-if="token">
    <uni-section class="mb-10" title="头像">
      <template v-slot:right>
        <!-- <image
					:src="userCodeStore.usercode.himg"
					style="width: 90rpx; height: 90rpx; border-radius: 50%"
					mode=""
				></image> -->
        <button
          v-if="shebei == 'mp-weixin'"
          class="avatar-wrapper"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
          style="width: 90rpx; height: 90rpx; padding: 0; border-radius: 50%"
        >
          <image
            class="avatar"
            style="width: 90rpx; height: 90rpx; border-radius: 50%"
            :src="userCodeStore.usercode.himg"
          ></image>
        </button>

        <button
          v-else
          class="avatar-wrapper"
          @click="changeAvatar"
          style="width: 90rpx; height: 90rpx; padding: 0; border-radius: 50%"
        >
          <image
            class="avatar"
            style="width: 90rpx; height: 90rpx; border-radius: 50%"
            :src="userCodeStore.usercode.himg"
          ></image>
        </button>
      </template>
    </uni-section>
    <uni-section class="mb-10" title="昵称" @click="goEdit">
      <template v-slot:right>{{ userCodeStore.usercode.nickname }}</template>
    </uni-section>
    <uni-section class="mb-10" title="是否开启动画">
      <template v-slot:right>
        <switch
          @change="ifAnimation"
          :checked="userCodeStore.usercode.animation == 1"
          color="#FFE60F"
          style="transform: scale(0.7)"
        />
      </template>
    </uni-section>

    <view class="logout" style="margin-top: 20rpx" @click="logOut">
      退出登录
    </view>
    <!--   <view class="logout" style="color: #9c9c9c" @click="delAccount">
      注销账号
    </view>
    <view
      class="logout"
      style="margin-top: 20rpx; font-size: 28rpx; color: #3d3d3d"
      @click="goRule(2)"
    >
      用户协议
    </view>
    <view
      class="logout"
      style="font-size: 28rpx; color: #3d3d3d"
      @click="goRule(3)"
    >
      隐私政策
    </view> -->

    <!-- 编辑昵称弹出层 -->
    <uni-popup ref="editpopup" type="center">
      <view class="editpopup-content">
        <view class="editpopup-title"> 编辑昵称 </view>
        <view class="editpopup-content-tow">
          <uni-easyinput
            @input="nickNameChange"
            v-model="nickname"
            :maxlength="7"
            trim="both"
            placeholder="请输入昵称"
          ></uni-easyinput>

          <view class=""> 一个月只能修改五次 </view>
        </view>
        <view class="editpopup-button">
          <view class="" @click="canceledit"> 取消 </view>
          <view class="" @click="editName"> 确定编辑 </view>
        </view>
      </view>
    </uni-popup>

    <!-- 注销弹出层 -->
    <uni-popup ref="accountpopup" type="center">
      <view class="accountpopup-content">
        <view class="accountpopup-title"> 注销 </view>
        <view class="accountpopup-content-tow">
          <view class=""> 确认是否注销账号？ </view>
        </view>
        <view class="accountpopup-button">
          <view class="" @click="cancelaccount"> 取消 </view>
          <view class="" @click="accountName"> 确定注销 </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  .setting-list {
    height: 100vh;
    padding: 20rpx 0;
    box-sizing: border-box;
    background-color: #f5f5f5;
    .logout {
      background-color: #fff;
      line-height: 102rpx;
      color: red;
      text-align: center;
    }
  }
  // ::v-deep .uni-section .uni-section-header {
  // 	height: 72rpx;
  // }
  .editpopup-content {
    width: 600rpx;
    height: 356rpx;
    padding: 0 30rpx;
    box-sizing: border-box;
    border-radius: 36rpx;
    background-color: #fff;
    .editpopup-title {
      height: 114rpx;
      border-bottom: 1px solid #d8d8d8;
      text-align: center;
      font-size: 40rpx;
      line-height: 114rpx;
    }
    .editpopup-content-tow {
      display: flex;
      align-items: center;
      flex-direction: column;
      line-height: 70rpx;
      text-align: center;
      font-size: 28rpx;
      color: #9b9b9d;
    }
    .editpopup-button {
      display: flex;
      align-items: center;
      justify-content: space-between;
      view {
        width: 234rpx;
        height: 80rpx;
        background-color: $all-color;
        border-radius: 40rpx;
        text-align: center;
        font-size: 26rpx;
        line-height: 80rpx;
        color: #3d3d3d;
        font-weight: 600;
        &:first-child {
          border: 2rpx solid #9b9b9d;
          background-color: #fff;
          color: #9b9b9d;
        }
      }
    }
  }
  .accountpopup-content {
    width: 600rpx;
    height: 356rpx;
    padding: 0 30rpx;
    box-sizing: border-box;
    border-radius: 36rpx;
    background-color: #fff;
    .accountpopup-title {
      height: 114rpx;
      border-bottom: 1px solid #d8d8d8;
      text-align: center;
      font-size: 40rpx;
      line-height: 114rpx;
    }
    .accountpopup-content-tow {
      display: flex;
      align-items: center;
      flex-direction: column;
      line-height: 112rpx;
      text-align: center;
      font-size: 28rpx;
      color: #9b9b9d;
    }
    .accountpopup-button {
      display: flex;
      align-items: center;
      justify-content: space-between;
      view {
        width: 234rpx;
        height: 80rpx;
        background-color: $all-color;
        border-radius: 40rpx;
        text-align: center;
        font-size: 26rpx;
        line-height: 80rpx;
        color: #3d3d3d;
        font-weight: 600;
        &:first-child {
          border: 2rpx solid #9b9b9d;
          background-color: #fff;
          color: #9b9b9d;
        }
      }
    }
  }
  ::v-deep .is-input-border {
    height: 60rpx !important;
  }
</style>
